package com.gxa.controller;

import com.gxa.common.Constants;
import com.gxa.common.ResponseData;
import com.gxa.pojo.Employee;
import com.gxa.realm.MyRealm;
import com.gxa.service.EmployeeService;
import com.gxa.utils.JwtUtils;
import com.gxa.utils.UuidUtil;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


/**
 * (Employee)表控制层
 *
 * @author makejava
 * @since 2020-10-26 19:32:35
 */
@RestController
@RequestMapping("system")
@Api(value = "系统设置",tags = "系统设置")
public class SystemController {
    @Autowired
    private ResponseData responseData;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private MyRealm myRealm;

    /**
     *登录
     * @param employee
     * @return
     */
    @PostMapping("login")
    @ApiOperation(value = "用户登录信息接口",notes = "根据提交信息完成用户登录",httpMethod = "POST", response = ResponseData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="登录成功"),
            @ApiResponse(code=400,message="登录失败"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "employeeUsername",value = "用户名",paramType = "query",required = true),
            @ApiImplicitParam(name = "employeePwd",value = "密码",paramType = "query",required = true),
            @ApiImplicitParam(name = "rememberMe",value = "记住我",paramType = "query"),
            @ApiImplicitParam(name = "verifycode",value = "验证码",paramType = "query",required = true)
    })
    @ResponseBody
    public ResponseData login(@RequestBody Employee employee) {
        System.out.println("employeeUsername="+employee.getEmployeeUsername()+" employeePwd="+employee.getEmployeePwd()+" rememberMe="+employee.getRememberMe());
        //得到主体
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            //获取Token : 从前端传

            UsernamePasswordToken token = new UsernamePasswordToken(employee.getEmployeeUsername(), employee.getEmployeePwd());
            System.out.println("token成功");
            //记住我
//            token.setRememberMe(rememberMe);
            //登录
            subject.login(token);
            System.out.println("登录成功");
        }
        Employee employee1=employeeService.findByEmployeeUsername(employee.getEmployeeUsername());
        String token= JwtUtils.createJwt(UuidUtil.getUUID(),"token",JwtUtils.generalSubject(employee.getEmployeeUsername()),JwtUtils.TTMILLIS);
        responseData.setCode(Constants.SUCCESS);
        responseData.setMsg("登录成功");
        responseData.setData(employee1);
        responseData.setToken(token);
        return responseData;
    }
    /**
     * 用户退出
     * @return
     */
    @PostMapping("logout")
    @ApiOperation(value = "用户退出接口",notes = "用户退出接口",httpMethod = "POST", response = ResponseData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="退出成功"),
            @ApiResponse(code=400,message="退出失败"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public ResponseData logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        responseData.setCode(Constants.SUCCESS);
        responseData.setMsg("退出成功");
        responseData.setData(null);
        responseData.setToken(null);
        return responseData;
    }

    /**
     * 修改个人信息
     * @return
     */
    @PostMapping("changePassword")
    @ApiOperation(value = "修改个人信息",notes = "修改个人信息接口",httpMethod = "POST", response = ResponseData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="修改成功"),
            @ApiResponse(code=400,message="修改失败"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "employeeUsername",value = "用户名",paramType = "query",required = true),
            @ApiImplicitParam(name = "oldPassword",value = "旧密码",paramType = "query",required = true),
            @ApiImplicitParam(name = "employeePwd",value = "新密码",paramType = "query",required = true)
    })
    @ResponseBody
    public ResponseData updateEmployeePwd(@RequestBody Employee employee){
        SimpleHash simpleHash = new SimpleHash("md5",employee.getOldPassword(),"jiami",2);
        Employee employee1 = employeeService.findByEmployeeUsername(employee.getEmployeeUsername());
        if (employee1.getEmployeePwd().equals(simpleHash.toString())){
            String s = new SimpleHash("md5", employee.getEmployeePwd(), "jiami", 2).toString();
            int result=employeeService.updateEmployeePwd(s,employee1.getEmployeeUsername());
            if (result>0){
                responseData.setCode(Constants.SUCCESS);
                responseData.setMsg("修改成功");
                responseData.setData(null);
            }else {
                responseData.setCode(Constants.FAILED);
                responseData.setMsg("修改失败");
                responseData.setData(null);
            }

        }else {
            responseData.setCode(Constants.FAILED);
            responseData.setMsg("修改失败");
            responseData.setData(null);
        }
        return responseData;
    }

    /**
     * 验证码
     * @param request
     * @param response
     * @return
     */
    @GetMapping("checkCode")
    public ResponseData checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 100;
        int height = 38;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0,0, width,height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        System.out.println("checkCode="+checkCode);
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
        String checkcode_server = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体",Font.BOLD,24));
        //向图片上写入验证码
        g.drawString(checkCode,15,25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image,"PNG",response.getOutputStream());
        responseData.setCode(200);
        responseData.setMsg("查询成功");
        responseData.setData(checkCode);
        responseData.setToken(null);
        return responseData;
    }
    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }
}